/*
 * InputStreamEntityWithProgress.java
 * 
 * Copyright©2012-2013 JMAS corporation. All rights reserved.
 */
package jp.co.jmas.jmasvideo.task;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * InputStreamEntityWithProgress
 * @author toshio
 * @see http://stackoverflow.com/questions/7057342/how-to-get-a-progress-bar-for-a-file-upload-with-apache-httpclient-4
 */
public class InputStreamEntityWithProgress extends org.apache.http.entity.InputStreamEntity {
	/** */
	private final int startProgress;

	private final int endProgress;

	private int bytesWritten;

	private final ProgressListener progressListener;

	private final long length;

	public InputStreamEntityWithProgress(InputStream instream, long length, int startProgress, int endProgress, ProgressListener progressListener) {
		super(instream, length);
		this.length           = length;
		this.startProgress    = startProgress;
		this.endProgress      = endProgress;
		this.progressListener = progressListener;
	}

	private void update() {
		int value  = Math.round((endProgress - startProgress) * bytesWritten / (float)length) + startProgress;
		progressListener.progressUpdate(value);
	}

	@Override
	public void writeTo(final OutputStream outstream) throws IOException {
		OutputStream streamWithProgress = new OutputStream() {
			@Override
			public void write(int oneByte) throws IOException {
				outstream.write(oneByte);
				bytesWritten++;
				update();
			}

			@Override
			public void write(byte[] buffer) throws IOException {
				outstream.write(buffer);
				bytesWritten += buffer.length;
				update();
			}

			@Override
			public void write(byte[] buffer, int offset, int count) throws IOException {
				outstream.write(buffer, offset, count);
				bytesWritten += count;
				update();
			}

			@Override
			public void flush() throws IOException {
				outstream.flush();
			}

			@Override
			public void close() throws IOException {
				outstream.close();
			}
		};

		super.writeTo(streamWithProgress);
	}

	public interface ProgressListener {
		public void progressUpdate(int progress);
	}
}

